﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CSF.Utility.Mvc;
using CSF.Security.Data;
using CSF.Utility.Security;
using CSF.Service.Accounts.Client;

namespace CSF.WebApp.Accounts.Controllers
{
    public class BaseController : SecureController
    {
        /// <summary>
        /// 应用程序Id
        /// </summary>
        protected Application _application = null;

        protected string _toUrl = null;

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.HttpContext.Request;

            if (!request.IsAuthenticated)
            {
                OnUnauthenticatedActionExecuting(filterContext);
            }
            else
            {
                ApplicationSvcClient svc = new ApplicationSvcClient();
                _application = svc.GetOneById(_userSession.ApplicationId);
                base.OnActionExecuting(filterContext);
            }
            _toUrl = request["toUrl"];
            if (string.IsNullOrWhiteSpace(_toUrl))
            {
                if (_application.DefaultUrl != null)
                {
                    _toUrl = _application.DefaultUrl;
                }
                else
                {
                    _toUrl = string.Empty;
                }
            }
            ViewBag.AppName = _application.Name1;
            ViewBag.AppLogo = _application.Logo;
            ViewBag.ToUrl = _toUrl;
        }

        private void OnUnauthenticatedActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.HttpContext.Request;

            string encryptCode = request["appCode"];
            string timeStamp = request["timeStamp"];


            filterContext.RouteData.Values.Add("appCode", encryptCode);
            filterContext.RouteData.Values.Add("timeStamp", timeStamp);
            filterContext.RouteData.Values.Add("toUrl", _toUrl);

            string appCode;
            bool bValid = false;
            try
            {
                bValid = AppCodec.Decode(encryptCode, timeStamp, out appCode);
                if (bValid)
                {
                    ApplicationSvcClient svc = new ApplicationSvcClient();
                    _application = svc.GetOneByCode(appCode);
                    if (_application == null)
                        bValid = false;
                }
            }
            catch (Exception)
            {
                bValid = false;
            }
            if (bValid)
            {
                base.OnActionExecuting(filterContext);
            }
            else
            {
                filterContext.Result = this.GoBack();
            }
        }

    }
}
